package com.oedtech.esl.service.nettyService;

import com.oedtech.esl.controller.WebSocketTest;
import com.oedtech.esl.service.eslService.ApService;
import com.oedtech.esl.socket.BsChannelMap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@ChannelHandler.Sharable
public class DataHandler extends ChannelInboundHandlerAdapter {

static AtomicInteger a=new AtomicInteger();
    private static Logger LOGGER = LoggerFactory.getLogger(DataHandler.class);
    @Autowired
    private DataService dataService;
    @Autowired
    private ApService apService;
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        try{
            if(buf.isReadable()) {
                byte[]arrays=new byte[buf.readableBytes()];

               buf.readBytes(arrays);
                int[]datas=new int[arrays.length];
                for(int i=0;i<arrays.length;i++){
                   datas[i]=arrays[i]&0xff;
               }
                dataService.dataManager(ctx.channel(),datas);
            }
        }finally {

            buf.release();
        }

    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
//         BsChannelMap.getInstance().values().remove(ctx.channel());
        Map<String,Channel> map=BsChannelMap.getInstance();

        for (Map.Entry<String, Channel> entry : map.entrySet()) {
            if(entry.getValue().equals(ctx.channel())){
                String apid=entry.getKey();
                map.remove(apid);
                apService.apOffLine(apid);


                LOGGER.warn("dataHandler--channelUnregistered--apid:[{}],channel:[{}]",entry.getKey(),ctx.channel());
                WebSocketTest.sendAll("apDisconnect",null,entry.getKey());
                break;
            }
        }
        ctx.close();
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        LOGGER.error("DataHandler--exception",cause);
            ctx.close();
    }

}
